from pdfminer.converter import PDFPageAggregator  # 转换器
from pdfminer.layout import LTTextBoxHorizontal, LAParams  # 布局
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter  # 解释器
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed  # 是否允许pdf和text转换
from pdfminer.pdfparser import PDFParser, PDFDocument


# pdf->txt
def readPdf(path, toPath):
    parser = PDFParser(open(path, "rb"))
    pdfFile = PDFDocument()
    parser.set_document(pdfFile)
    pdfFile.set_parser(parser)
    pdfFile.initialize()

    if not pdfFile.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        manager = PDFResourceManager()
        laparams = LAParams()
        device = PDFPageAggregator(manager, laparams=laparams)
        # 解释器对象
        interpreter = PDFPageInterpreter(manager, device)
        # 开始循环处理，每次处理一页
        for page in pdfFile.get_pages():
            interpreter.process_page(page)
            layout = device.get_result()
            for x in layout:
                if isinstance(x, LTTextBoxHorizontal):
                    with open(toPath, "a") as f:
                        str = x.get_text()
                        f.write(str + "\n")


path = r"../resource/image/input/test.pdf"
toPath = r"../image/output/pdfTo.txt"
readPdf(path, toPath)
